package com.tiny.codegen.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.Map;

import freemarker.cache.FileTemplateLoader;
import freemarker.cache.NullCacheStorage;
import freemarker.cache.TemplateLoader;
import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateExceptionHandler;

/**
 * 配置模板路径
 * 
 * @author Tiny</br>
 *         mail: 114740122@qq.com
 * @date 2018年7月10日  
 * @version 1.0
 */
public class FreeMarkerTemplateUtil {
	private String templateDir = null;

	private final Configuration CONFIGURATION = new Configuration(Configuration.VERSION_2_3_22);

	public FreeMarkerTemplateUtil(String dir) throws IOException {
		this.templateDir = dir;
		// 这里比较重要，用来指定加载模板所在的路径
		TemplateLoader templateLoader = null;
		templateLoader = new FileTemplateLoader(new File(templateDir + "/template"));
		CONFIGURATION.setTemplateLoader(templateLoader);
		CONFIGURATION.setDefaultEncoding("UTF-8");
		CONFIGURATION.setTemplateExceptionHandler(TemplateExceptionHandler.RETHROW_HANDLER);
		CONFIGURATION.setCacheStorage(NullCacheStorage.INSTANCE);
	}

	private Template getTemplate(String templateName) throws IOException {
		try {
			return CONFIGURATION.getTemplate(templateName);
		} catch (IOException e) {
			throw e;
		}
	}

	public void clearCache() {
		CONFIGURATION.clearTemplateCache();
	}

	/**
	 * 生成文件
	 * 
	 * @param templateDir
	 * @param templateName
	 * @param dir
	 * @param fileName
	 * @param dataMap
	 * @throws Exception
	 */
	public void generateFileByTemplate(String templateName, String dir, String fileName, Map<String, Object> dataMap)
			throws Exception {
		FileOutputStream fos = null;
		try {
			File fileDir = new File(dir);
			if (!fileDir.exists()) {
				fileDir.mkdirs();
			}
			File file = new File(dir, fileName);
			if (file.exists()) {
				file.delete();
			}
			Template template = getTemplate(templateName);
			fos = new FileOutputStream(file);

			dataMap.put("StringUtil", new StringUtil());
			Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
			System.out.println(templateName + "生成的文件的路径->" + file.getPath());
			template.process(dataMap, out);
		} finally {
			if (null != fos) {
				fos.close();
			}
		}
	}

}
